<template>
  <el-dialog
    title="人员选择"
    :close-on-click-modal="false"
    :visible.sync="sortingPerChooseDialogData.visible"
    width="90vw"
    top="5vh"
    append-to-body
  >
    <el-container>
      <el-main style="height: 70vh; overflow-x: hidden">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="5">
            <div class="boxsty">
              <el-tree
                :data="treeData"
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                :default-expanded-keys="[1]"
                accordion
                @node-click="getNodeData"
              />
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="7">
            <div class="boxsty">
              <div class="flex titbottom">
                <el-input
                  v-model="listQuery.name"
                  placeholder="请输入搜索用户"
                  style="margin-right: 10px"
                ></el-input>
                <el-button
                  @click="btnSearch"
                  type="primary"
                  icon="el-icon-search"
                  plain
                  >搜索</el-button
                >
              </div>
              <div class="avue-crud">
                <el-table
                  @row-click="handleClick"
                  :data="tableDataDept"
                  v-loading="tableloading"
                  style="width: 100%"
                >
                  <el-table-column prop="username" label="用户" width="120">
                  </el-table-column>
                  <el-table-column prop="ryName" label="姓名" min-width="150">
                  </el-table-column>
                </el-table>
              </div>
              <div style="margin-top: 20px">
                <el-pagination
                  @size-change="sizeChangeHandle"
                  @current-change="currentChangeHandle"
                  :current-page="page.currentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="page.pageSize"
                  :total="page.total"
                  background
                  layout="total, sizes, prev, pager, next"
                >
                </el-pagination>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <div class="boxsty">
              <div class="tabletext titbottom">已选择人员</div>
              <div class="avue-crud">
                <el-table
                  :data="tableDataUser"
                  ref="ry-table"
                  class="avue-cruds"
                  row-key="userId"
                >
                  <el-table-column
                    prop="sx"
                    label="顺序"
                    width="90"
                  ></el-table-column>
                  <el-table-column prop="userName" label="姓名" width="130">
                  </el-table-column>
                  <el-table-column
                    prop="deptName"
                    label="部门"
                    min-width="220"
                  ></el-table-column>
                  <el-table-column fixed="right" label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        @click="delUserList(scope.$index)"
                        type="danger"
                        plain
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="btnSave">确定</el-button>
      <el-button type="primary" plain @click="btnCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import store from "@/store";
import { fetchList } from "@/api/admin/user";
import { shouyuetree, fayuetree1 } from "@/api/hetongrenwu/hetongyeji/hetongnd";
import { validatenull } from "@/util/validate";
import { tuisongwenben } from "@/api/hetongrenwu/hetongyeji/hetongnd";
import { submitStatusAll } from "@/api/hetongrenwu/hetongyeji/hetongnd";
import {
  handleSubmitAll,
  handleSubmitAllByht,
} from "@/api/hetongrenwu/hetongjgtb";
import { jghzsubmitAll } from "@/api/hetongrenwu/hetongjghz";
import { saveTemplatehang } from "@/api/dailyExamine/eventExamine/sjtemplate";
import { saveTemplateUser } from "@/api/dailyExamine/eventExamine/sjtemplate";
import { alldepeuser } from "@/api/dailyExamine/eventExamine/sjtemplate";
import { mydept } from "@/api/dailyExamine/eventExamine/sjtemplate";
import { showJgTree,fetchUserList,getKpiTreeAll } from "@/api/dailyExamine/targetExamine/createAssessment";
import { fetchTree } from "@/api/admin/dept.js";
import Sortable from "sortablejs";
export default {
  props: {
    sortingPerChooseDialogData: {},
  },
  data() {
    return {
      type: "",
      types: "",
      qjDeptId: "", //全局部门id
      tableloading: false, //table遮挡
      tableDataDept: [],
      tableDataUser: [],
      listQuery: {
        name: "",
      },
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false, // 是否倒序
      },
      searchForm: {},
      nodeKey: [],
      rows: [],
      ids: "",
      objdata: "",
      loading: null,
    };
  },
  mounted() {},
  created() {},
  watch: {
    sortingPerChooseDialogData: {
      handler(newVal, oldVal) {
        console.log(newVal);
        if (newVal.visible) {
          this.rows = newVal.rows;
          this.types = newVal.types;
          this.objdata = newVal.objdata;
          this.getList();
        }
        if (newVal.types == "allChoose") {
          this.tableDataUser = newVal.perLsit.reverse();
        }
      },
    },
  },
  methods: {
    getList() {
      if (this.types == "wbsh" || this.types == "jghz") {
        shouyuetree(this.listQuery).then((response) => {
          this.treeData = response.data.data;
        });
      } else if (
        this.types == "zbnd" ||
        this.types == "jgtb" ||
        this.types == "jgtbde" ||
        this.types == "jghzNd" ||
        this.types == "temper"
      ) {
        fayuetree1().then((response) => {
          this.treeData = response.data.data;
        });
      } else if (this.types == "allChoose") {
          getKpiTreeAll().then(response => {
              if(response.data.data == "allTree"){
                  fetchTree().then(res => {
                      this.treeData = res.data.data;
                  });
              }else{
                  this.treeData = response.data.data;

              }
        });
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getPersons(page, params) {
      this.tableloading = true;
      fetchUserList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableDataDept = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableloading = false;
        })
        .catch((err) => {
          this.tableloading = false;
        });
    },
    getNodeData(data) {
      this.page.currentPage = 1;
      this.qjDeptId = data.id;
      this.getPersons(this.page, {
        deptId: data.id,
      });
    },
    //选人添加到右边的框
    handleClick(vm) {
      if (this.type != "jg") {
        for (var i = 0; i < this.tableDataUser.length; i++) {
          if (this.tableDataUser[i].userId == vm.userId) {
            return;
          }
        }
      }
      let objUser = {};
      objUser["userId"] = vm.userId;
      objUser["userName"] = vm.ryName;
      objUser["deptName"] = vm.deptName;
      this.tableDataUser.unshift(objUser);
      var lengths = this.tableDataUser.length + 1;
      this.tableDataUser.forEach((ele) => {
        lengths--;
        ele.sx = lengths;
      });
      this.rowDrop();
    },
    //删除人员list
    delUserList(index) {

        if(this.tableDataUser.length != 1){
            this.tableDataUser.splice(index, 1);
            this.rowDrop();
        }else{
            this.$message.warning("人员数据不能为空");
            return false;
        }

    },
    //清空记录
    clearDataList() {
      this.qjDeptId = "";
      this.tableDataDept = [];
      this.tableDataUser = [];
    },
    //保存人员
    btnSave() {
      this.tableDataUser.reverse().forEach((ele) => {
        this.ids = this.ids.concat(ele.userId, ",");
      });
      var params = {
        rows: this.rows,
        sonhq: this.ids,
        objdata: this.objdata,
      };
      var params2 = {
        rows: this.rows,
        sonhq: this.ids,
        objdata: this.objdata,
        istemplate: 0,
      };
      console.log(this.ids);
      if (this.types == "wbsh") {
        tuisongwenben(params2)
          .then((res) => {
            this.$message.closeAll();
            this.$message.success("推送文本审核成功");
            this.sortingPerChooseDialogData.visible = false;
            this.$emit("sortingPerChooseDialogChild", res);
            this.tableDataUser = [];
          })
          .catch(() => {
            this.loading.close();
            this.$message.closeAll();
            this.$message({
              type: "error",
              message: "推送失败!",
            });
          });
      } else if (this.types == "zbnd") {
        var zbndparams = {
          rows: this.rows,
          sonhq: this.ids,
          iszbsh: 1,
        };
        submitStatusAll(zbndparams)
          .then((res) => {
            this.loading.close();
            this.$message.closeAll();
            this.$message.success("提交成功");
            this.sortingPerChooseDialogData.visible = false;
            this.$emit("sortingPerChooseDialogChild", res);
            this.tableDataUser = [];
          })
          .catch(() => {
            this.loading.close();
            this.$message.closeAll();
            this.$message({
              type: "error",
              message: "推送失败!",
            });
          });
      } else if (this.types == "jgtb") {
        var jgtbshparams = {
          rows: this.rows,
          sonhq: this.ids,
          isjgtbsh: 1,
        };
        handleSubmitAll(jgtbshparams)
          .then((res) => {
            this.loading.close();
            this.$message.closeAll();
            this.$message.success("提交成功");
            this.sortingPerChooseDialogData.visible = false;
            this.$emit("sortingPerChooseDialogChild", res);
            this.tableDataUser = [];
          })
          .catch(() => {
            this.loading.close();
            this.$message.closeAll();
            this.$message({
              type: "error",
              message: "推送失败!",
            });
          });
      } else if (this.types == "jgtbde") {
        handleSubmitAllByht(params)
          .then((res) => {
            this.loading.close();
            this.$message.closeAll();
            this.$message.success("提交成功");
            this.sortingPerChooseDialogData.visible = false;
            this.$emit("sortingPerChooseDialogChild", res);
            this.tableDataUser = [];
          })
          .catch(() => {
            this.loading.close();
            this.$message.closeAll();
            this.$message({
              type: "error",
              message: "推送失败!",
            });
          });
      } else if (this.types == "jghz") {
        jghzsubmitAll(params2)
          .then((res) => {
            this.loading.close();
            this.$message.closeAll();
            this.$message.success("提交成功");
            this.sortingPerChooseDialogData.visible = false;
            this.$emit("sortingPerChooseDialogChild", res);
            this.tableDataUser = [];
          })
          .catch(() => {
            this.loading.close();
            this.$message.closeAll();
            this.$message({
              type: "error",
              message: "推送失败!",
            });
          });
      } else if (this.types == "jghzNd") {
        //console.log( this.objdata)
        var perids = "";
        this.tableDataUser.reverse().forEach((ele) => {
          perids = perids + ele.userId + ",";
        });
        this.loading.close();
        this.sortingPerChooseDialogData.visible = false;
        this.$emit("sortingPerChooseDialogChild", perids);
        this.tableDataUser = [];
      } else if (this.types == "allChoose") {
        this.sortingPerChooseDialogData.rows.isjump =
          !this.sortingPerChooseDialogData.rows.isjump;
        this.sortingPerChooseDialogData.rows.userjson = JSON.stringify(
          this.tableDataUser.reverse()
        );
          saveTemplateUser(this.sortingPerChooseDialogData.rows).then((res) => {
          if (res.data.data == "保存成功！") {
            this.$message.closeAll();
            this.$message.success("审批人员保存成功");
            this.sortingPerChooseDialogData.visible = false;
            this.$emit("sortingPerChooseDialogChild", this.tableDataUser.reverse());
          }else if(res.data.data == "保存失败！") {
              this.$message.closeAll();
              this.$message.warning(res.data.msg);
              this.sortingPerChooseDialogData.visible = false;
              this.$emit("sortingPerChooseDialogChild");
          }

        });
        this.loading.close();
        this.sortingPerChooseDialogData.visible = false;
        this.tableDataUser = [];
      }/* else if (this.types == "allChoose") {
        this.$emit("sortingPerChooseDialogChild", this.tableDataUser.reverse());
        this.sortingPerChooseDialogData.visible = false;
      }*/
    },
    // tree搜索事件,搜索人
    btnSearch() {
      let param = {
        deptId: this.qjDeptId,
      };

      if (this.listQuery.name.trim() !== "") {
        param["username"] = this.listQuery.name.trim();
        param["ryName"] = this.listQuery.name.trim();
      }
      this.getPageUsers(param);
    },
    // 分页
    // 每页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      this.getPageUsers();
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.currentPage = val;
      this.getPageUsers();
    },
    //分页刷新
    getPageUsers(vm) {
      if (vm) {
        this.getPersons(this.page, vm);
      } else {
        this.getPersons(this.page, {
          deptId: this.qjDeptId,
        });
      }
    },
    //取消按钮
    btnCancel() {
      this.sortingPerChooseDialogData.visible = false;
      this.clearDataList();
    },
    /**
     * excel 导出
     */
    exportExcel() {
      try {
        // 导出
        require.ensure([], () => {
          const { export_json_to_excel } = require("@/util/Export2Excel");
          const tHeader = "用户,姓名,部门".split(",");
          const filterVal = "xsUserName,ryName,deptName".split(",");
          const list = this.tableDataUser.map((column) =>
            filterVal.map((header) => {
              return column[header];
            })
          );
          export_json_to_excel(tHeader, list, "已选人员名单");
        });
      } catch (e) {
        if (typeof console !== "undefined") console.error(e);
      }
    },
    //判空
    validatenull(val) {
      return validatenull(val);
    },
    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector(
        ".avue-cruds .el-table__body-wrapper tbody"
      );
      //console.log(tbody)
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableDataUser.splice(oldIndex, 1)[0];
          _this.tableDataUser.splice(newIndex, 0, currRow);
        },
      });
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped>
</style>
